import $pacsApi from '@/api/pacs'

const state = {
  exchagneAlertShow: false,
  exchangeCompleteCount: 0,
  exchangeTotalCount: 0,
  exchangeTimeId: null,
  exchangeState: false
}

const mutations = {
  SET_ALERT_SHOW (state, payload) {
    console.log('state, payload', state, payload)
    state.exchagneAlertShow = payload
  },
  CLEAR_TIME_ID (state) {
    clearInterval(state.exchangeTimeId)
    state.exchangeTimeId = null
  },
  SET_COMPLETE_COUNT (state, payload) {
    state.exchangeCompleteCount = payload
  },
  SET_TOTAL_COUNT (state, payload) {
    state.exchangeTotalCount = payload
  },
  SET_FINALY_STATE (state, payload) {
    state.exchangeState = payload
  }
}

const actions = {
  pollingGetExchangeProgressRate({ commit, state }) { // 轮询获取影像发送进度
    if(state.exchangeTimeId) { // 目前有进行中的定时任务
      commit('CLEAR_TIME_ID') // 清除定时器
    }else {
      state.exchangeTimeId = setInterval(async () => {
        let res = await $pacsApi.pacsApi.getExchangeProgressRate()
        let { code, data } = res
        if(code === 0) {
          if(data.total_count === -1) { // 没有进行中的任务，返回-1
            // commit('SET_COMPLETE_COUNT', 0)
            // commit('SET_TOTAL_COUNT', 0)
            commit('SET_COMPLETE_COUNT', data.complete_count)
            commit('SET_TOTAL_COUNT', data.total_count)
            commit('CLEAR_TIME_ID') // 清除定时器
            commit('SET_FINALY_STATE', true)
          }else {
            commit('SET_COMPLETE_COUNT', data.complete_count)
            commit('SET_TOTAL_COUNT', data.total_count)
          }
        }
      }, 1000)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
